package com.example.netchat;

import com.example.netchat.ContentUtils.Room;

import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.MenuItem;

public class ChatActivity extends FragmentActivity implements
		ChatFragment.ActionListener {
	public static final String EXTRA_ROOM_ID = "roomId";
	private Room mRoom;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Configuration config = getResources().getConfiguration();
		if ((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE
				&& config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			startActivity(MainActivity.createEnterRoomIntent(
					getApplicationContext(),
					getIntent().getStringExtra(EXTRA_ROOM_ID)));
			finish();
			return;
		}

		setContentView(R.layout.activity_chat);
		setupNavigation();

		handleIntent(getIntent(), savedInstanceState);
	}

	private void handleIntent(Intent intent, Bundle savedInstanceState) {
		this.mRoom = ContentUtils.getRoomByRoomId(this,
				intent.getStringExtra(EXTRA_ROOM_ID));

		setTitle(this.mRoom.name);

		if (findViewById(R.id.fragment_container) != null) {

			if (savedInstanceState != null) {
				return;
			}

			// Create an instance of ExampleFragment
			ChatFragment chatFragment = new ChatFragment();

			Bundle bundle = new Bundle();

			bundle.putString(ChatFragment.ARGUMENT_ROOM_ID,
					intent.getStringExtra(EXTRA_ROOM_ID));
			chatFragment.setArguments(bundle);

			getSupportFragmentManager().beginTransaction()
					.add(R.id.fragment_container, chatFragment).commit();
		}

		((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
				.cancel(R.id.chat_notification + (int) this.mRoom._id);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		handleIntent(intent, null);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
		}

		return super.onOptionsItemSelected(item);
	}

	@TargetApi(11)
	private void setupNavigation() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	public static Intent createChatIntent(Context context, String roomId) {
		Intent intent = new Intent(context, ChatActivity.class);

		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra(EXTRA_ROOM_ID, roomId);

		return intent;
	}

	@Override
	public void onRoomDelete() {
		finish();
	}
}
